#include <fal.h>
#include <sfud.h>

/* 手动添加 */
#define FAL_USING_SFUD_PORT

#ifdef FAL_USING_SFUD_PORT
#ifdef RT_USING_SFUD
#include <spi_flash_sfud.h>
#endif

#ifndef FAL_USING_NOR_FLASH_DEV_NAME
#endif

static int init(void);

static int read(long offset, uint8_t *buf, size_t size);

static int write(long offset, const uint8_t *buf, size_t size);

static int erase(long offset, size_t size);

static sfud_flash_t sfud_dev = NULL;

struct fal_flash_dev spi_flash = {
        .name       = FAL_USING_NOR_FLASH_DEV_NAME,
        .addr       = 0,
        .len        = 16 * 1024 * 1024,  /* 修正为 16MB */
        .blk_size   = 4096,  /* 默认擦除块大小 4KB */
        .ops        = {init, read, write, erase},
        .write_gran = 1
};

static int init(void) {
#ifdef RT_USING_SFUD
    /* 如果是 RT-Thread 平台，使用 RT-Thread SFUD 接口 */
    sfud_dev = rt_sfud_flash_find_by_dev_name(FAL_USING_NOR_FLASH_DEV_NAME);
#else
    /* 裸机或非 RT-Thread 平台，直接使用 SFUD API */
    sfud_dev = sfud_get_device(SFUD_W25Q128_DEVICE_INDEX);  /* 确保这里的索引正确 */
#endif

    if (NULL == sfud_dev) {
        return -1;
    }

    /* 更新 Flash 设备信息 */
    spi_flash.blk_size = sfud_dev->chip.erase_gran;
    spi_flash.len = sfud_dev->chip.capacity;  /* 自动适配 Flash 大小 */

    return 0;
}

static int read(long offset, uint8_t *buf, size_t size) {
    assert(sfud_dev);
    assert(sfud_dev->init_ok);

    return sfud_read(sfud_dev, spi_flash.addr + offset, size, buf) == SFUD_SUCCESS ? size : -1;
}

static int write(long offset, const uint8_t *buf, size_t size) {
    assert(sfud_dev);
    assert(sfud_dev->init_ok);

    return sfud_write(sfud_dev, spi_flash.addr + offset, size, buf) == SFUD_SUCCESS ? size : -1;
}

static int erase(long offset, size_t size) {
    assert(sfud_dev);
    assert(sfud_dev->init_ok);

    return sfud_erase(sfud_dev, spi_flash.addr + offset, size) == SFUD_SUCCESS ? size : -1;
}

#endif /* FAL_USING_SFUD_PORT */
